package com.sun.dailyprj.androidx.workmanager;

import android.app.Activity;
import android.os.Build;
import android.os.Bundle;
import android.view.View;

import com.sun.dailyprj.R;
import com.sun.dailyprj.databinding.ActivityWorkerBinding;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.databinding.DataBindingUtil;
import androidx.work.Constraints;
import androidx.work.Data;
import androidx.work.OneTimeWorkRequest;
import androidx.work.WorkManager;

/*
 * =====================================================================================
 * Summary:
 *
 * File: WorkerActivity.java
 * Author: Yanpeng.Sun
 * Create: 2019/6/21 16:12
 * =====================================================================================
 */
public class WorkerActivity extends Activity{
    ActivityWorkerBinding mBinding;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mBinding = DataBindingUtil.setContentView(this, R.layout.activity_worker);

        mBinding.setWork(this);
        mBinding.btnWorkCreate.setOnClickListener(new View.OnClickListener(){
            @RequiresApi(api = Build.VERSION_CODES.M)
            @Override
            public void onClick(View v) {
                //给Worker传入参数
                Data data = new Data.Builder()
                        .putString("picUri","uri:cccc")
                        .build();
                //定义TimeWorker的约束
                Constraints constraints = new Constraints.Builder()
                        .setRequiresCharging(true)
                        .setRequiresDeviceIdle(true)
                        .build();
                OneTimeWorkRequest timeWorkRequest = new OneTimeWorkRequest.Builder(TimerWorker.class)
                       // .setInitialDelay(5, TimeUnit.SECONDS)
                        .setConstraints(constraints)
                        .setInputData(data)  //给work传入data中包含参数
                        .build();

                //定义了工作请求之后，现在可以使用workmanager使用enqueue（）方法对其进行调度。
                WorkManager.getInstance().enqueue(timeWorkRequest);
                //可以发现app死后，重启，worker任务会自动执行
            }
        });
    }
}
